local H = require "packages/new_heg/util"
local U = require "packages/utility/utility"
local extension = Package:new("policy")
extension.extensionName = "hegemony_diy"
extension.game_modes_whitelist = { 'nos_heg_mode', 'new_heg_mode' }

Fk:loadTranslationTable{
  ["policy"] = "日月交辉·策",
  ["wk_heg"] = "日月",
}

--- 战策一·金鼓齐鸣
local policy1 = fk.CreateTriggerSkill{
  name = "drum_together",
  events = {fk.Damage},
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and target == player
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "drum_together_ask")
  end,
  on_use = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      if H.compareKingdomWith(p, player) and not p.dead then
        p:drawCards(1, self.name)
      end
    end
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-drum_together", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策二·偃甲息兵
local policy2 = fk.CreateTriggerSkill{
  name = "backarm_stop",
  events = {fk.TargetConfirmed},
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    local from = player.room:getPlayerById(data.from)
    return player:getMark(mark_name) ~= 0 and target == player and from ~= player and (#from:getCardIds("e") > 0 or #player:getCardIds("e") > 0)
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "backarm_stop_ask")
  end,
  on_use = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    local room = player.room
    local from = room:getPlayerById(data.from)
    room:moveCardTo(player:getCardIds("e"), Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, false, player.id)
    local mark_player = player:getTableMark("@steam__mianzhou-turn")
    table.insertIfNeed(mark_player, "equip_char")
    room:setPlayerMark(player, "@@backarm_stop-turn", mark_player)
    
    room:moveCardTo(from:getCardIds("e"), Card.PlayerHand, from, fk.ReasonJustMove, self.name, nil, false, player.id)
    local mark_from = from:getTableMark("@steam__mianzhou-turn")
    table.insertIfNeed(mark_from, "equip_char")
    room:setPlayerMark(from, "@@backarm_stop-turn", mark_from)
    
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-backarm_stop", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

local policy2_prohibit = fk.CreateProhibitSkill{
  name = "#backarm_stop_prohibit",
  prohibit_use = function(self, player, card)
    return card.type == Card.TypeEquip and table.contains(player:getTableMark("@@backarm_stop-turn"), "equip_char")
  end,
}
policy2:addRelatedSkill(policy2_prohibit)

--- 战策三·李代桃僵
local policy3 = fk.CreateTriggerSkill{
  name = "other_replace",
  events = {fk.DamageInflicted},
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and not player.dead and player ~= target and data.damage >= target.hp
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "other_replace_ask")
  end,
  on_use = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    local room = player.room
    player:drawCards(1, self.name)
    room:damage{
      from = data.from,
      to = player,
      damage = data.damage,
      skillName = self.name,
    }
    data.damage = 0
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-other_replace", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策四·反守为攻
local policy4 = fk.CreateTriggerSkill{
  name = "reverse_attack",
  events = {fk.CardUseFinished, fk.CardRespondFinished},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and target == player and data.responseToEvent and data.responseToEvent.card
     and player.room:getPlayerById(data.responseToEvent.from) ~= player
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "reverse_attack_ask")
  end,
  on_use = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    local room = player.room
    local to = room:getPlayerById(data.responseToEvent.from)
    if to.dead then return end
    room:useVirtualCard("slash", nil, player, {to}, self.name)
    room:setPlayerMark(player, mark_name, 0) 
    room:handleAddLoseSkills(player, "-reverse_attack", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策五·声东击西
local policy5 = fk.CreateTriggerSkill{
  name = "trueaim_another",
  events = {fk.AfterCardTargetDeclared},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and data.from == player.id and #TargetGroup:getRealTargets(data.tos) == 1 
     and (data.card.type == Card.TypeBasic or data.card:isCommonTrick())
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = TargetGroup:getRealTargets(data.tos)
    local chooses = table.map(room:getOtherPlayers(player), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, chooses, 1, #targets, "trueaim_another_ask", self.name, true)
    if #tos ~= 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local mark_name = "@[private]"..self.name.."_mark"
    data.tos = {}
    local to = self.cost_data
    for i = 1, #to, 1 do
      TargetGroup:pushTargets(data.tos, to[i])
    end
    room:setPlayerMark(player, mark_name, 0) 
    room:handleAddLoseSkills(player, "-trueaim_another", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策六·招兵买马
local policy6 = fk.CreateTriggerSkill{
  name = "buy_arm",
  events = {fk.EventPhaseStart},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and player.phase == Player.Start and target == player
  end,
  on_cost = function(self, event, target, player, data) 
    local card = player.room:askForDiscard(player, 1, 1, false, self.name, true, ".", "buy_arm_ask", true)
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local mark_name = "@[private]"..self.name.."_mark"
    local pattern = "equip"
    local card
    local cards = {}
    room:throwCard(self.cost_data, self.name, player, player)
    local _pattern = ".|.|.|.|.|equip"
    if #room:getCardsFromPileByRule(_pattern, 1) == 0 then return false end
    while true do
      local id = room:getNCards(1)[1]
      room:moveCardTo(id, Card.Processing, nil, fk.ReasonJustMove, self.name)
      room:delay(300)
      local c = Fk:getCardById(id)
      if c:getColorString() == pattern or c:getTypeString() == pattern then
        card = c
        break
      else
        table.insert(cards, id)
      end
    end
    room:moveCardTo(card.id, Player.Hand, player, fk.ReasonPrey, self.name, nil, true, player.id)
    cards = table.filter(cards, function(id) return room:getCardArea(id) == Card.Processing end)
    room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, nil, true, player.id)
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-buy_arm", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策七·暗度陈仓
local policy7 = fk.CreateTriggerSkill{
  name = "move_insecret",
  events = {fk.EventPhaseStart},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    local targets = {}
    local logic = player.room.logic
    logic:getEventsOfScope(GameEvent.UseCard, 99, function (e)
      if e.data[1].card.trueName == "jink" or e.data[1].card.trueName == "nullification" then
        table.insertIfNeed(targets, e.data[1].from)
      end
    end, Player.HistoryTurn)
    self.cost_data = targets
    return player:getMark(mark_name) ~= 0 and player.phase == Player.Finish and #targets > 0
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local tos = room:askForChoosePlayers(player, self.cost_data, 1, 1, "move_insecret_ask", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local mark_name = "@[private]"..self.name.."_mark"
    local to = room:getPlayerById(self.cost_data[1])
    room:damage{
      from = player,
      to = to,
      damage = 1,
      skillName = self.name,
    }
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-move_insecret", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策八·绝处逢生
local policy8 = fk.CreateTriggerSkill{
  name = "getlive_indeath",
  events = {fk.EnterDying},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and player == target and not player:isKongcheng()
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "getlive_indeath_ask")
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local mark_name = "@[private]"..self.name.."_mark"
    player:throwAllCards("h")
    room:recover{
      who = player,
      num = 1,
      recoverBy = player,
      skillName = self.name,
    }
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-getlive_indeath", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策九·趁火打劫
local policy9 = fk.CreateTriggerSkill{
  name = "attack_infire",
  events = {fk.EnterDying},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and player ~= target and #target:getCardIds("heg") > 0
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "attack_infire_ask")
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local mark_name = "@[private]"..self.name.."_mark"
    local cards = U.askforCardsChosenFromAreas(player, target, "hej", self.name, nil, nil, false)
    room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonGive, self.name, nil, false, player.id)
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-attack_infire", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策十·偷梁换柱
local policy10 = fk.CreateTriggerSkill{
  name = "replace_something",
  events = {fk.EventPhaseStart},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and target.phase == Player.Play and player ~= target and player:distanceTo(target) == 1 and not target:isKongcheng() and not player:isKongcheng()
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "replace_something_ask")
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local mark_name = "@[private]"..self.name.."_mark"
    local cards = target:getCardIds(Player.Hand)
    local handcards = player:getCardIds(Player.Hand)
    cards = U.askForExchange(player, "needhand", "wordhand", cards, handcards, ".", 1)
    if #cards == 0 then return false end
    handcards = table.filter(cards, function (id)
      return table.contains(handcards, id)
    end)
    cards = table.filter(cards, function (id)
      return not table.contains(handcards, id)
    end)
    U.swapCards(room, player, player, target, handcards, cards, self.name)
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-replace_something", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 交换副将
---@param room Room
---@param player ServerPlayer
---@param target ServerPlayer
---@return boolean
local function SwapTwoPlayersDeputy(room, player, target)
  if not (player.deputyGeneral and target.deputyGeneral) then return false end
  if player.deputyGeneral == "anjiang" then player:revealGeneral(true, true) end
  if target.deputyGeneral == "anjiang" then target:revealGeneral(true, true) end
  local general1 = player.deputyGeneral
  local general2 = target.deputyGeneral
 
  room:changeHero(player, "blank_shibing", false, true, false, false, false)
  room:changeHero(target, "blank_shibing", false, true, false, false, false)
  room:changeHero(player, general2, false, true, true, false, false)
  room:changeHero(target, general1, false, true, true, false, false)
  return true
end

--- 战策十一·调兵遣将
local policy11 = fk.CreateTriggerSkill{
  name = "move_people",
  events = {fk.EventPhaseStart},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and target == player and player.phase == Player.Finish
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p)
      return H.compareKingdomWith(p, player)
    end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "move_people_ask", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local mark_name = "@[private]"..self.name.."_mark"
    local to = room:getPlayerById(self.cost_data[1])
    if to ~= player then
      SwapTwoPlayersDeputy(room, player, to)
    end  
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-move_people", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

--- 战策十二·见缝插针
local policy12 = fk.CreateTriggerSkill{
  name = "getchance_insmall",
  events = {fk.TargetConfirming},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local mark_name = "@[private]"..self.name.."_mark"
    return player:getMark(mark_name) ~= 0 and target ~= player and data.card.trueName ~= "threaten_emperor" and
    (data.card:isCommonTrick() or data.card.type == Card.TypeBasic) and U.isOnlyTarget(target, data, event) and U.canTransferTarget(player, data)
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local cards = room:askForDiscard(player, 1, 1, true, self.name, true, ".", "getchance_insmall_ask", true)
    if #cards > 0 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local mark_name = "@[private]"..self.name.."_mark"
    room:throwCard(self.cost_data, self.name, player, player)
    local targets = {player.id}
    if type(data.subTargets) == "table" then
      table.insertTable(targets, data.subTargets)
    end
    AimGroup:addTargets(player.room, data, targets)
    room:setPlayerMark(player, mark_name, 0)
    room:handleAddLoseSkills(player, "-getchance_insmall", nil, false)
    room.logic:trigger("fk.HegLosePolicy", player, {player, self.name})
  end,
}

Fk:addSkill(policy1)
Fk:addSkill(policy2)
Fk:addSkill(policy3)
Fk:addSkill(policy4)
Fk:addSkill(policy5)
Fk:addSkill(policy6)
Fk:addSkill(policy7)
Fk:addSkill(policy8)
Fk:addSkill(policy9)
Fk:addSkill(policy10)
Fk:addSkill(policy11)
Fk:addSkill(policy12)

Fk:loadTranslationTable{
  ["drum_together"] = "战策",
  ["backarm_stop"] = "战策",
  ["other_replace"] = "战策",
  ["reverse_attack"] = "战策",
  ["trueaim_another"] = "战策",
  ["buy_arm"] = "战策",
  ["move_insecret"] = "战策",
  ["getlive_indeath"] = "战策",
  ["attack_infire"] = "战策",
  ["replace_something"] = "战策",
  ["move_people"] = "战策",
  ["getchance_insmall"] = "战策",

  [":drum_together"] = "战策",
  [":backarm_stop"] = "战策",
  [":other_replace"] = "战策",
  [":reverse_attack"] = "战策",
  [":trueaim_another"] = "战策",
  [":buy_arm"] = "战策",
  [":move_insecret"] = "战策",
  [":getlive_indeath"] = "战策",
  [":attack_infire"] = "战策",
  [":replace_something"] = "战策",
  [":move_people"] = "战策",
  [":getchance_insmall"] = "战策",

  ["@[drum_together_mark]"] = "金鼓齐鸣",
  ["@[backarm_stop_mark]"] = "偃甲息兵",
  ["@[other_replace_mark]"] = "李代桃僵",
  ["@[reverse_attack_mark]"] = "反守为攻",
  ["@[trueaim_another_mark]"] = "声东击西",
  ["@[buy_arm_mark]"] = "招兵买马",
  ["@[move_insecret_mark]"] = "暗度陈仓",
  ["@[getlive_indeath_mark]"] = "绝处逢生",
  ["@[attack_infire_mark]"] = "趁火打劫",
  ["@[replace_something_mark]"] = "偷梁换柱",
  ["@[move_people_mark]"] = "调兵遣将",
  ["@[getchance_insmall_mark]"] = "见缝插针",

  ["drum_together_ask"] = "战策-金鼓齐鸣：你可以令所有与你势力相同的角色各摸一张牌",
  ["backarm_stop_ask"] = "战策-偃甲息兵：你可以令你与此牌使用者依次收回装备区内所有牌且本回合不能使用装备牌",
  ["other_replace_ask"] = "战策-李代桃僵：你可以防止此伤害，然后你摸一张牌且伤害来源对你造成等量伤害",
  ["reverse_attack_ask"] = "战策-反守为攻：你可以视为对此牌使用者使用一张【杀】",
  ["trueaim_another_ask"] = "战策-声东击西：你可以重新指定一名其他角色为此牌的目标",
  ["buy_arm_ask"] = "战策-招兵买马：你可以弃置一张牌，检索并获得一张装备牌",
  ["move_insecret_ask"] = "战策-暗度陈仓：你可以选择一名本回合使用过【闪】或【无懈可击】的角色，对其造成1点伤害",
  ["getlive_indeath_ask"] = "战策-绝处逢生：你可以弃置所有手牌，回复1点体力",
  ["attack_infire_ask"] = "战策-趁火打劫：你可以获得其区域内各一张牌",
  ["replace_something_ask"] = "战策-偷梁换柱：你可以观看当前角色所有手牌并用一张手牌交换其中一张",
  ["move_people_ask"] = "战策-调兵遣将：你可以与一名与你势力相同的角色交换副将",
  ["getchance_insmall_ask"] = "战策-见缝插针：你可以弃置一张牌，成为此牌的额外目标",
}

--- 获得战策
---@param room Room
---@param player ServerPlayer
---@param num integer
---@param skillName string
local function GetPolicy(room, player, num, skillName)
  local all_policies = { "drum_together", "backarm_stop", "other_replace", "reverse_attack", "trueaim_another", "buy_arm",
          "move_insecret", "getlive_indeath", "attack_infire", "replace_something", "move_people", "getchance_insmall"}
  for _, p in ipairs(room.alive_players) do
    for _, s in ipairs(p.player_skills) do
      if table.contains(all_policies, s.name) then
        table.removeOne(all_policies, s.name)
      end
    end
  end
  local count = num
  if #all_policies < num then count = #all_policies end
  if count == 0 then return end
  local policies = table.random(all_policies, count)
  for i = 1, #policies, 1 do
    room:handleAddLoseSkills(player, policies[i], nil, false)
    U.setPrivateMark(player, policies[i].."_mark", { "@["..policies[i].."_mark]" })
  end  
  room:doBroadcastNotify("ShowToast", Fk:translate(player.general) .. '/' .. Fk:translate(player.deputyGeneral) .. " " .. Fk:translate("#PolicyGet") .. " " .. Fk:translate(num) .. " " ..Fk:translate("#PolicyCard"))
  room:sendLog{
    type = "#GetPolicyLog",
    from = player.id,
    arg = count,
    arg2 = skillName,
  }
end

--- 获得某角色战策数量
---@param player ServerPlayer
local function GetPolicyNum(player)
  local all_policies = { "drum_together", "backarm_stop", "other_replace", "reverse_attack", "trueaim_another", "buy_arm",
          "move_insecret", "getlive_indeath", "attack_infire", "replace_something", "move_people", "getchance_insmall"}
  local policies = {}
  for _, s in ipairs(player.player_skills) do
    if table.contains(all_policies, s.name) then
      table.insertIfNeed(policies, s.name)
    end
  end
  return #policies
end

Fk:loadTranslationTable{
  ["@@backarm_stop-turn"] = "偃甲息兵",

  ["#PolicyGet"] = "获得了",
  ["#PolicyCard"] = "战策",

  ["@[private]drum_together_mark"] = "战策",
  ["@[private]backarm_stop_mark"] = "战策",
  ["@[private]other_replace_mark"] = "战策",
  ["@[private]reverse_attack_mark"] = "战策",
  ["@[private]trueaim_another_mark"] = "战策",
  ["@[private]buy_arm_mark"] = "战策",
  ["@[private]move_insecret_mark"] = "战策",
  ["@[private]getlive_indeath_mark"] = "战策",
  ["@[private]attack_infire_mark"] = "战策",
  ["@[private]replace_something_mark"] = "战策",
  ["@[private]move_people_mark"] = "战策",
  ["@[private]getchance_insmall_mark"] = "战策",

  ["#GetPolicyLog"] = "%from 由于 “%arg2”，获得了 %arg 张“战策”。",
}

local zhaoang = General(extension, "wk_heg__zhaoang", "wei", 4)
local xieyu = fk.CreateTriggerSkill{
  name = "wk_heg__xieyu",
  events = {fk.HpLost, fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    if event == fk.HpLost then
      return player:hasSkill(self) and H.compareKingdomWith(player, target) and GetPolicyNum(target) < target.maxHp
    else
      return player:hasSkill(self) and player.phase == Player.Finish
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.HpLost then
      GetPolicy(room, target, 1, self.name)
    else
      local targets = table.map(room:getOtherPlayers(player), Util.IdMapper)
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__xieyu_choose", self.name, false)
      room:setPlayerMark(player, "wk_heg__xieyu_src", 1)
      local to = room:getPlayerById(tos[1])
      room:setPlayerMark(player, "@@wk_heg__xieyu", 1)
      room:setPlayerMark(to, "@@wk_heg__xieyu", 1)
    end
  end,

  refresh_events = {fk.TurnStart, fk.Death},
  can_refresh = function(self, event, target, player, data)
    if target == player then
      if event == fk.TurnStart then
        return player:getMark("wk_heg__xieyu_src") ~= 0
      else
        return player:getMark("@@wk_heg__xieyu") ~= 0
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      for _, p in ipairs(room.alive_players) do
        room:setPlayerMark(p, "@@wk_heg__xieyu", 0)
        room:setPlayerMark(p, "wk_heg__xieyu_use", 0)
      end
      room:setPlayerMark(player, "wk_heg__xieyu_src", 0)
    else
      if player:getMark("wk_heg__xieyu_src") ~= 0 then
        room:setPlayerMark(player, "@@wk_heg__xieyu", 0)
      else
        for _, p in ipairs(room.alive_players) do
          room:setPlayerMark(p, "@@wk_heg__xieyu", 0)
          room:setPlayerMark(p, "wk_heg__xieyu_use", 0)
        end
        room:setPlayerMark(player, "wk_heg__xieyu_src", 0)
      end
    end
  end,
}

local xieyu_trigger = fk.CreateTriggerSkill{
  name = "#wk_heg__xieyu_trigger",
  mute = true,
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return player:getMark("@@wk_heg__xieyu") ~= 0 and target ~= player 
     and target:getMark("@@wk_heg__xieyu") ~= 0 and player:getMark("wk_heg__xieyu_use") == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "wk_heg__xieyu_use", 1)
    if room:askForSkillInvoke(player, xieyu.name, nil, "#wk_heg__xieyu-loseHp::"..target.id) then
      player:broadcastSkillInvoke(xieyu.name)
      room:notifySkillInvoked(player,  xieyu.name, "support")
      room:loseHp(player, 1, xieyu.name)
      return true
    end
  end,
}

xieyu:addRelatedSkill(xieyu_trigger)
zhaoang:addSkill(xieyu)
Fk:loadTranslationTable{
  ["wk_heg__zhaoang"] = "赵昂",
  ["#wk_heg__zhaoang"] = "",
    
  ["designer:wk_heg__zhaoang"] = "24&教父",
  ["wk_heg__xieyu"] = "协御",
  [":wk_heg__xieyu"] = "①与你势力相同的角色失去体力后，若其“战策”数小于其体力上限，你可令其获得一张“战策”；②结束阶段，你可选择一名其他角色，直至你下回合开始，当你/其下次受到伤害时，其/你可失去1点体力防止之<br />"..
  "<font color = 'gray'>战策：部分角色可以获得“战策”，获得“战策”时，其随机从“战策”库中抽取等量的“战策”并视为拥有此“战策”对应的效果；拥有“战策”的角色可以在对应的时机发动“战策”上的效果，然后将此“战策”洗回“战策”堆。</font>",

  ["#wk_heg__xieyu_choose"] = "协御：你可以选择一名其他角色，当你/其下次受到伤害时，其/你可失去1点体力防止之",
  ["@@wk_heg__xieyu"] = "协御",
  ["@zhiwei"] = "至微",
  ["#wk_heg__xieyu_trigger"] = "协御",
  ["#wk_heg__xieyu-loseHp"] = "协御：%dest 受到伤害，你可以失去1点体力防止之",
  ["$wk_heg__xieyu1"] = "",
  ["$wk_heg__xieyu2"] = "",
  
  ["~wk_heg__zhaoang"] = "",
}

local jiangji = General(extension, "wk_heg__jiangji", "wei", 3)

---@param object Card|Player
---@param markname string
---@param suffixes string[]
---@return boolean
local function hasMark(object, markname, suffixes)
  if not object then return false end
  for mark, _ in pairs(object.mark) do
    if mark == markname then return true end
    if mark:startsWith(markname .. "-") then
      for _, suffix in ipairs(suffixes) do
        if mark:find(suffix, 1, true) then return true end
      end
    end
  end
  return false
end

local jilun_alliance1 = fk.CreateActiveSkill{
  name = "alliance1&",
  prompt = "#alliance1&",
  anim_type = "support",
  can_use = function(self, player)
    return table.find(player:getCardIds(Player.Hand), function(id) return hasMark(Fk:getCardById(id), "@@alliance", MarkEnum.CardTempMarkSuffix) end)
     and player:usedSkillTimes("alliance&", Player.HistoryPhase) == 99
  end,
  max_card_num = 3,
  min_card_num = 1,
  card_filter = function(self, to_select, selected)
    return hasMark(Fk:getCardById(to_select), "@@alliance", MarkEnum.CardTempMarkSuffix) 
     and table.contains(Self.player_cards[Player.Hand], to_select) and #selected + Self:getMark("wk_heg__alliance1-phase") < 3
  end,
  target_num = 1,
  target_filter = function(self, to_select, selected, selected_cards)
    if #selected == 0 and #selected_cards >= 1 and #selected_cards <= 3 then
      return H.canAlliance(Self, Fk:currentRoom():getPlayerById(to_select))
    end
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    local player = room:getPlayerById(effect.from)
    local ret = H.compareKingdomWith(target, player, true)
    room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, true, player.id)
    if ret and not player.dead then
      player:drawCards(#effect.cards, self.name)
    end
    room:addPlayerMark(player, "wk_heg__alliance1-phase", #effect.cards)
  end
}

local jilun_alliance2 = fk.CreateActiveSkill{
  name = "alliance2&",
  prompt = "#alliance2&",
  anim_type = "support",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and player:usedSkillTimes("alliance&", Player.HistoryPhase) == 99
     and table.find(player:getCardIds(Player.Hand), function(id) return hasMark(Fk:getCardById(id), "@@alliance", MarkEnum.CardTempMarkSuffix) end)
  end,
  max_card_num = 99,
  min_card_num = 1,
  card_filter = function(self, to_select, selected)
    return hasMark(Fk:getCardById(to_select), "@@alliance", MarkEnum.CardTempMarkSuffix) and table.contains(Self.player_cards[Player.Hand], to_select) and #selected <= 99
  end,
  target_num = 1,
  target_filter = function(self, to_select, selected, selected_cards)
    if #selected == 0 and #selected_cards >= 1 and #selected_cards <= 99 then
      return H.canAlliance(Self, Fk:currentRoom():getPlayerById(to_select))
    end
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    local player = room:getPlayerById(effect.from)
    local ret = H.compareKingdomWith(target, player, true)
    room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, true, player.id)
    if ret and not player.dead then
      player:drawCards(#effect.cards, self.name)
    end
  end
}

local jilun_alliance3 = fk.CreateActiveSkill{
  name = "alliance3&",
  prompt = "#alliance3&",
  anim_type = "support",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and player:usedSkillTimes("alliance&", Player.HistoryPhase) == 99
     and table.find(player:getCardIds(Player.Hand), function(id) return hasMark(Fk:getCardById(id), "@@alliance", MarkEnum.CardTempMarkSuffix) end)
  end,
  max_card_num = 3,
  min_card_num = 1,
  card_filter = function(self, to_select, selected)
    return hasMark(Fk:getCardById(to_select), "@@alliance", MarkEnum.CardTempMarkSuffix) and table.contains(Self.player_cards[Player.Hand], to_select) and #selected <= 3
  end,
  target_num = 1,
  target_filter = function(self, to_select, selected, selected_cards)
    if #selected == 0 and #selected_cards >= 1 and #selected_cards <= 3 then
      return Self ~= Fk:currentRoom():getPlayerById(to_select)
    end
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    local player = room:getPlayerById(effect.from)
    local ret = H.compareKingdomWith(target, player, true)
    room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, true, player.id)
    if ret and not player.dead then
      player:drawCards(#effect.cards, self.name)
    end
  end
}

local jilun = fk.CreateTriggerSkill{
  name = "wk_heg__jilun",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove, fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return player:hasSkill(self) and player == target and player.phase == Player.Start
    else
      for _, move in ipairs(data) do
        if move.moveReason == fk.ReasonDiscard and move.from and move.from == player.id and not player.dead then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              return player:hasSkill(self)
            end
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return true
    else
      -- local room = player.room
      -- local targets = table.map(table.filter(room.alive_players, function(p)
      --   return p:getHandcardNum() == player:getHandcardNum() end), Util.IdMapper)
      -- local tos = room:askForChoosePlayers(player, targets, 1, 1, "wk_heg__jilun_pro", self.name, true)
      -- if tos then
      --   self.cost_data = tos[1]
      --   return true
      -- end
      return player.room:askForSkillInvoke(player, self.name, nil, "wk_heg__shiju_discard")
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local choices = {"wk_heg__jilun_change1", "wk_heg__jilun_change2", "wk_heg__jilun_change3"}
      local choice = room:askForChoice(player, choices, self.name)
      local mark_num = 0
      if choice == "wk_heg__jilun_change1" then
        mark_num = 1
        room:handleAddLoseSkills(player, "alliance1&", nil)
      elseif choice == "wk_heg__jilun_change2" then
        mark_num = 2
        room:handleAddLoseSkills(player, "alliance2&", nil)
      else
        mark_num = 3
        room:handleAddLoseSkills(player, "alliance3&", nil)
      end
      room:setPlayerMark(player, "wk_heg__jilun_alliance", mark_num)
    else
      -- local to = room:getPlayerById(self.cost_data)
      -- to:drawCards(1, self.name)
      room:askForDiscard(room.current, 1, 1, false, self.name, false)
    end
  end,

  refresh_events = {fk.TurnStart, fk.TurnEnd},
  can_refresh = function(self, event, target, player, data)
    if event == fk.TurnStart then
      return player:getMark("wk_heg__jilun_alliance") > 0 and player == target
    else
      return player:getMark("wk_heg__jilun_alliance_change") > 0 and player == target
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      local mark_num = player:getMark("wk_heg__jilun_alliance")
      if mark_num == 1 then
        room:handleAddLoseSkills(player, "-alliance1&", nil)
      elseif mark_num == 2 then
        room:handleAddLoseSkills(player, "-alliance2&", nil)
      elseif mark_num == 3 then
        room:handleAddLoseSkills(player, "-alliance3&", nil)
      end
      room:setPlayerMark(player, "wk_heg__jilun_alliance", 0)
    else
      local mark_num = player:getMark("wk_heg__jilun_alliance_change")
      if mark_num == 1 then
        room:handleAddLoseSkills(player, "-alliance1&", nil)
      elseif mark_num == 2 then
        room:handleAddLoseSkills(player, "-alliance2&", nil)
      elseif mark_num == 3 then
        room:handleAddLoseSkills(player, "-alliance3&", nil)
      end
      room:setPlayerMark(player, "wk_heg__jilun_alliance_change", 0)
    end
  end,
}

local jilun_forbidden = fk.CreateTriggerSkill{
  name = "#wk_heg__jilun_forbidden",
  anim_type = "special",
  events = {fk.EventPhaseStart, "fk.AllianceSkillChanged"},
  can_trigger = function(self, event, target, player, data)
    if not (player == target and ((player:getMark("wk_heg__jilun_alliance") > 0) or (player:getMark("wk_heg__jilun_alliance_change") > 0))) then return false end
    if event == fk.EventPhaseStart then
      return player.phase == Player.Play
    else
      return true
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player:setSkillUseHistory("alliance&", 99, Player.HistoryPhase)
  end
}

---@param markname string
---@param suffixes string[]
---@return boolean
local function hasMark(object, markname, suffixes)
  if not object then return false end
  for mark, _ in pairs(object.mark) do
    if mark == markname then return true end
    if mark:startsWith(markname .. "-") then
      for _, suffix in ipairs(suffixes) do
        if mark:find(suffix, 1, true) then return true end
      end
    end
  end
  return false
end

local shiju = fk.CreateTriggerSkill{
  name = "wk_heg__shiju",
  anim_type = "defensive",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p)
      return H.compareKingdomWith(p, player) end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "wk_heg__shiju_pro", self.name, true)
    if tos then
      local to = room:getPlayerById(tos[1])
      local choices = {}
      if player ~= to and not to:isNude() and player:getMark("wk_heg__jilun_alliance") > 0 then
        table.insert(choices, "wk_heg__shiju_change")
      end
      -- if not to:prohibitUse(Fk:cloneCard("slash")) and to:canUseCardTo() data.damage.from ~= to.id then
      if not to:prohibitUse(Fk:cloneCard("slash")) then
        table.insert(choices, "wk_heg__shiju_slash")
      end
      if #choices == 0 then return false end
      local choice = room:askForChoice(to, choices, self.name)
      if choice == "wk_heg__shiju_change" then
        local cards = room:askForCard(to, 1, 1, false, self.name, false, ".", "#wk_heg__shiju-give")
        room:obtainCard(player, cards, false, fk.ReasonGive)
        local mark_alliance = player:getMark("wk_heg__jilun_alliance")
        room:setPlayerMark(to, "wk_heg__jilun_alliance_change", mark_alliance)
        if mark_alliance == 1 then
          room:handleAddLoseSkills(to, "alliance1&", nil)
        elseif mark_alliance == 2 then
          room:handleAddLoseSkills(to, "alliance2&", nil)
        elseif mark_alliance == 3 then
          room:handleAddLoseSkills(to, "alliance3&", nil)
        end
        room.logic:trigger("fk.AllianceSkillChanged", to, nil)
      else
        -- local slash_targets = table.map(table.filter(room:getAlivePlayers(false), function(p)
        --   return p ~= to end), Util.IdMapper)
        -- local slash_tos = room:askForChoosePlayers(player, slash_targets, 1, 1, "wk_heg__shiju_slash_choose", self.name, true)
        -- if slash_tos then
        --   room:useVirtualCard("slash", nil, to, room:getPlayerById(slash_tos[1]), self.name, true)
        -- end
        local card
        local cards = {}
        local _pattern = ".|.|.|.|.|basic"
        if #room:getCardsFromPileByRule(_pattern, 1) == 0 then return false end
        while true do
          local id = room:getNCards(1)[1]
          room:moveCardTo(id, Card.Processing, nil, fk.ReasonJustMove, self.name)
          room:delay(300)
          local c = Fk:getCardById(id)
          if c:getTypeString() == "basic" or hasMark(c, "@@alliance", MarkEnum.CardTempMarkSuffix) then
            card = c
            break
          else
            table.insert(cards, id)
          end
        end
        room:moveCardTo(card.id, Player.Hand, to, fk.ReasonPrey, self.name, nil, true, player.id)
        cards = table.filter(cards, function(id) return room:getCardArea(id) == Card.Processing end)
        room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, nil, true, player.id)
      end
    end
  end,
}

jiangji:addCompanions("hs__simayi")
jilun:addRelatedSkill(jilun_forbidden)
Fk:addSkill(jilun_alliance1)
Fk:addSkill(jilun_alliance2)
Fk:addSkill(jilun_alliance3)
jiangji:addSkill(jilun)
jiangji:addSkill(shiju)
Fk:loadTranslationTable{
  ["wk_heg__jiangji"] = "蒋济", 
  ["#wk_heg__jiangji"] = "江淮骨鲠",
  ["designer:wk_heg__jiangji"] = "祭祀&教父",
  ["wk_heg__jilun"] = "机论",
  [":wk_heg__jilun"] = "锁定技，①准备阶段，你修改一项你的“合纵”规则至你下回合开始；②当你因弃置而失去牌后，你可以令当前回合角色弃置一张手牌。<br />"..
  "<font color = 'orange'>合纵修改方式：1.删去“出牌阶段限一次”限制；2.删去“至多三张”限制；3.删去“与你势力不同或未确定势力的角色”限制</font>",
  ["wk_heg__shiju"] = "势举",
  [":wk_heg__shiju"] = "当你受到伤害后，你可以令一名与你势力相同的角色选择一项：1.交给你一张牌，其“合纵”规则改为与你相同直至其回合结束；2.检索并获得一张基本牌或带有“合纵”标记的牌。",

  ["wk_heg__jilun_change1"] = "合纵A 取消“出牌阶段限一次”限制",
  ["wk_heg__jilun_change2"] = "合纵B 取消“至多三张手牌”限制",
  ["wk_heg__jilun_change3"] = "合纵C 取消“其他势力角色”限制",

  ["alliance1&"] = "合纵A",
  [":alliance1&"] = "出牌阶段，你可将有“合”标记的合计至多三张手牌交给与你势力不同或未确定势力的一名角色，若你以此法交给与你势力不同的角色牌，你摸等量的牌。",
  ["#alliance1&"] = "合纵A：你可将至多3张有“合”标记的手牌交给势力不同或无势力的角色，前者你摸等量的牌",

  ["alliance2&"] = "合纵B",
  [":alliance2&"] = "出牌阶段限一次，你可将有“合”标记的任意张手牌交给与你势力不同或未确定势力的一名角色，若你以此法交给与你势力不同的角色牌，你摸等量的牌。",
  ["#alliance2&"] = "合纵B：你可将任意张有“合”标记的手牌交给势力不同或无势力的角色，前者你摸等量的牌",

  ["alliance3&"] = "合纵C",
  [":alliance3&"] = "出牌阶段限一次，你可将有“合”标记的至多三张手牌交给一名角色，若你以此法交给与你势力不同的角色牌，你摸等量的牌。",
  ["#alliance3&"] = "合纵C：你可将至多3张有“合”标记的手牌交给一名角色，若与你势力不同，你摸等量的牌",

  ["#wk_heg__jilun_forbidden"] = "机论",
  ["wk_heg__shiju_discard"] = "机论：你可以令当前回合角色弃置一张手牌",

  ["wk_heg__shiju_change"] = "修改“合纵”规则",
  ["wk_heg__shiju_slash"] = "检索并获得牌",
  ["wk_heg__shiju_pro"] = "势举：你可以选择一名与你势力相同的角色，其修改“合纵”规则与你相同或检索并获得牌",
  ["#wk_heg__shiju-give"] = "势举：请选择一张牌",
  ["wk_heg__shiju_slash_choose"] = "势举：请选择【杀】的目标",

  ["$wk_heg__shiju1"] = "此危亡之时，当出此急谋。",
  ["$wk_heg__shiju2"] = "急筹布画，运策捭阖。",
  ["$wk_heg__jilun1"] = "时移不移，违天之祥也。",
  ["$wk_heg__jilun2"] = "民望不因，违人之咎也。",
  ["~wk_heg__jiangji"] = "洛水之誓，言犹在耳……咳咳咳",
}

local manchong = General(extension, "wk_heg__manchong", "wei", 4)
manchong.mainMaxHpAdjustedValue = -1
local fuyu = fk.CreateTriggerSkill{
  name = "wk_heg__fuyu",
  anim_type = "control",
  events = {fk.CardUseFinished, fk.CardRespondFinished},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and data.responseToEvent and data.responseToEvent.card
     and not H.compareKingdomWith(player.room:getPlayerById(data.responseToEvent.from), player)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(data.responseToEvent.from)
    if to.dead then return end
    if not to.chained then
      to:setChainState(true)
    else
      room:damage{
        from = player,
        to = to,
        damage = 1,
        skillName = self.name,
      }
    end
  end,
}

local kaoxun = fk.CreateActiveSkill{
  name = "wk_heg__kaoxun",
  relate_to_place = "m",
  anim_type = "offensive",
  prompt = "#wk_heg__kaoxun_pro",
  can_use = Util.TrueFunc,
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 1,
  target_filter = function(self, to_select, selected, selected_cards)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and target.chained and target ~= Self
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    target:setChainState(false)
    if not target.dead and not target:isKongcheng() then
      local cards = room:askForCardChosen(player, target, "h", self.name)
      local card = Fk:getCardById(cards)
      room:throwCard(cards, self.name, target, player)
      if card.is_damage_card and not target.dead and not player.dead then
        H.askCommandTo(player, target, self.name, true)
      end
    end
  end,
}

local lishi = fk.CreateTriggerSkill{
  name = "wk_heg__lishi",
  relate_to_place = "d",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and target ~= player and target.phase == Player.Finish) then return false end 
    local targets = {}
    player.room.logic:getActualDamageEvents(1, function(e)
      local damage = e.data[1]
      if H.compareKingdomWith(player, damage.to) then
        table.insertIfNeed(targets, damage.to.id)
      end
      return false
    end)
    if #targets > 0 then
      self.cost_data = targets
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = room:askForChoosePlayers(player, self.cost_data, 1, 1, "wk_heg__lishi_pro", self.name, true)
    if tos then
      local to = room:getPlayerById(tos[1])
      -- to:reset()
      -- if not to.dead and not to:isNude() then
      local use = U.askForPlayCard(room, to, nil, ".", self.name, "#wk_heg__lishi_use", nil, true)
      if use then
        room:useCard(use)
      else
        to:reset()
      end
    end
  end,
}

manchong:addSkill(fuyu)
manchong:addSkill(kaoxun)
manchong:addSkill(lishi)
Fk:loadTranslationTable{
  ["wk_heg__manchong"] = "满宠", 
  ["#wk_heg__manchong"] = "政法兵谋",
  ["designer:wk_heg__manchong"] = "小曹神",
  ["wk_heg__fuyu"] = "伏御",
  [":wk_heg__fuyu"] = "当你响应与你势力不同角色使用的牌后，你可令其横置，若其已横置，则改为你对其造成1点伤害。",
  ["wk_heg__kaoxun"] = "拷讯",
  [":wk_heg__kaoxun"] = "主将技，此武将牌上单独的阴阳鱼个数-1；出牌阶段，你可令一名已横置的其他角色重置并弃置其一张手牌，若此牌为伤害类牌，你对其发起强制执行的“军令”。",
  ["wk_heg__lishi"] = "励势",
  [":wk_heg__lishi"] = "副将技，其他角色的结束阶段，你可令一名本回合受到过伤害的与你势力相同的角色选择复原武将牌或使用一张牌。",

  ["#wk_heg__kaoxun_pro"] = "拷讯：你可以展示一名已横置其他角色的一张牌，若为伤害类牌，你对其造成1点伤害",
  ["wk_heg__lishi_pro"] = "励势：选择一名本回合受到过伤害的角色复原武将牌或使用一张牌",
  ["#wk_heg__lishi_use"] = "励势：你可以使用一张牌，或点“取消”复原武将牌",
 
  ["$wk_heg__kaoxun1"] = "严刑峻法，以破奸诡之胆。",
  ["$wk_heg__kaoxun2"] = "你招还是不招？",
  ["$wk_heg__fuyu1"] = "御敌之策，成竹于胸。",
  ["$wk_heg__fuyu2"] = "以缓制急，不战屈兵。",
  ["$wk_heg__lishi1"] = "敌军围困万千重，我自岿然不动。。",
  ["$wk_heg__lishi2"] = "行伍严整，百战不殆。",
  ["~wk_heg__manchong"] = "援军为何迟迟未到……",
}

local liuyin = General(extension, "wk_heg__liuyin", "shu", 4)
local luoshou = fk.CreateTriggerSkill{
  name = "wk_heg__luoshou",
  anim_type = "defensive",
  events = {fk.CardUseFinished, fk.CardRespondFinished},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and GetPolicyNum(player) < player.maxHp and player == target) then return false end
    return data.responseToEvent and data.responseToEvent.card and player.room:getPlayerById(data.responseToEvent.from) ~= player
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    GetPolicy(room, player, 1, self.name)
  end,
}

-- local luoshou_maxcards = fk.CreateTriggerSkill{
--   name = "#wk_heg__luoshou_maxcards",
--   anim_type = "defensive",
--   events = {fk.EventPhaseStart},
--   frequency = Skill.Compulsory,
--   can_trigger = function(self, event, target, player, data)
--     return player:hasSkill(luoshou.name) and player.phase == Player.Discard and GetPolicyNum(player) > 0
--   end,
--   on_use = function(self, event, target, player, data)
--     local num = GetPolicyNum(player)
--     local room = player.room
--     room:addPlayerMark(player, MarkEnum.AddMaxCardsInTurn, num)
--   end,
-- }

-- luoshou:addRelatedSkill(luoshou_maxcards)
liuyin:addSkill(luoshou)
Fk:loadTranslationTable{
  ["wk_heg__liuyin"] = "柳隐",
  ["#wk_heg__liuyin"] = "",
    
  ["designer:wk_heg__liuyin"] = "24",
  ["wk_heg__luoshou"] = "略守",
  [":wk_heg__luoshou"] = "当你响应其他角色使用的牌结算后，若你的“战策”数小于你体力上限，你可获得一张“战策”。"..
  "<font color = 'gray'>战策：部分角色可以获得“战策”，获得“战策”时，其随机从“战策”库中抽取等量的“战策”并视为拥有此“战策”对应的效果；拥有“战策”的角色可以在对应的时机发动“战策”上的效果，然后将此“战策”洗回“战策”堆。</font>",

  ["#wk_heg__luoshou_maxcards"] = "略守",
  ["$wk_heg__luoshou1"] = "",
  ["$wk_heg__luoshou2"] = "",
  
  ["~wk_heg__liuyin"] = "",
}


local zhugezhan = General(extension, "wk_heg__zhugezhan", "shu", 4, 4, General.Male)
zhugezhan.deputyMaxHpAdjustedValue = -1
local zuilun = fk.CreateTriggerSkill{
  name = "wk_heg__zuilun",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  mute = true,
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target == player and player.phase == Player.Finish
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    local all_choices = {"wk_heg__zuilun-chain", "wk_heg__zuilun-discard", "wk_heg__zuilun-losehp"}
    local choices = table.clone(all_choices)
    for i = 3, 1, -1 do
      local c = all_choices[i]
      if player:getMark(c) > 0 then
        table.remove(choices, i)
      end
    end
    if #choices == 0 then
      room:notifySkillInvoked(player, self.name, "offensive")
      local targets = table.map(room:getOtherPlayers(player), Util.IdMapper)
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "wk_heg__zuilun-choose", self.name, false)
      local to = room:getPlayerById(tos[1])
      room:damage{
        from = player,
        to = to,
        damage = 1,
        skillName = self.name,
      }
    else
      room:notifySkillInvoked(player, self.name, "negative")
      local choice = room:askForChoice(player, choices, self.name, nil, false, all_choices)
      if choice == "wk_heg__zuilun-chain" then
        player:setChainState(true)
      elseif choice == "wk_heg__zuilun-discard" then
        local n = player:getHandcardNum() - 1
        if n > 0 then
          room:askForDiscard(player, n, n, false, self.name, false)
        end
      elseif choice == "wk_heg__zuilun-losehp" then
        local n = player.hp - 1
        if n > 0 then
          room:loseHp(player, n, self.name)
        end
      end
      room:setPlayerMark(player, choice, 1)
    end
  end,
}

local longfei = fk.CreateTriggerSkill{
  name = "wk_heg__longfei",
  array_type = "formation",
  relate_to_place = "m",
}

local longfeiTrig = fk.CreateTriggerSkill{
  name = "#wk_heg__longfei_trigger",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(longfei) and #player.room.alive_players >= 4 and H.inFormationRelation(player, target) 
     and target.phase == Player.Start and player:hasShownSkill(longfei)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, longfei.name)
    player:broadcastSkillInvoke(longfei.name)
    local num = 0
    for _, p in ipairs(room.alive_players) do
      if H.inFormationRelation(p, player) then
        num = num + 1
      end
    end
    room:askForGuanxing(player, room:getNCards(num))
  end,
}

--- 交换主副将
---@param room Room
---@param player ServerPlayer
---@return boolean
local function SwapMainAndDeputy(room, player)
  local general1 = player.general
  local general2 = player.deputyGeneral
  if not (general1 and general2) then return false end
  if general1 == "anjiang" then player:revealGeneral(false, true) end
  if general2 == "anjiang" then player:revealGeneral(true, true) end
  general1 = player.general
  general2 = player.deputyGeneral
  if string.find(general1, "lord") 
   or string.find(general1, "zhonghui") or string.find(general1, "simazhao")
   or string.find(general1, "sunchen") or string.find(general1, "gongsunyuan")
  then return false end
  room:changeHero(player, "blank_shibing", false, true, false, false, false)
  room:changeHero(player, general2, false, false, true, false, false)
  room:changeHero(player, general1, false, true, true, false, false)
  return true
end

local kuangzhis = fk.CreateTriggerSkill{
  name = "wk_heg__kuangzhis",
  anim_type = "special",
  relate_to_place = "d",
  events = {fk.Damage, fk.AfterDying},
  can_trigger = function (self, event, target, player, data)
    if event == fk.Damage then
      if not (player:hasSkill(self) and H.compareKingdomWith(player, target) and player.room.current == target) then return false end
      local events = player.room.logic:getActualDamageEvents(1, function(e)
        return e.data[1].from == target
      end, Player.HistoryTurn)
      return #events == 1 and events[1].data[1] == data
    else
      return player:hasSkill(self) and target and not target.dead and player == target
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.Damage then
      return player.room:askForSkillInvoke(player, self.name, nil, "wk_heg__kuangzhis-drawcard")
    else
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.Damage then
      if not target.dead then
        target:drawCards(1, self.name)
      end
      if not player.dead and player ~= target then
        player:drawCards(1, self.name)
      end
    else
      SwapMainAndDeputy(room, player)
      local targets = {}
      local n = -1
      for _, p in ipairs(room.alive_players) do
        if H.compareKingdomWith(p, player, true) then
          if p:getHandcardNum() > n then
            targets = {p.id}
            n = p:getHandcardNum()
          elseif p:getHandcardNum() == n then
            table.insert(targets, p.id)
          end
        end
      end
      if #targets == 0 then return end
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "wk_heg__kuangzhis-choose", self.name, false)
      local to = room:getPlayerById(tos[1])
      room:useVirtualCard("duel", nil, player, to, self.name)
    end
  end,
}

zhugezhan:addSkill(zuilun)
longfei:addRelatedSkill(longfeiTrig)
zhugezhan:addSkill(longfei)
zhugezhan:addSkill(kuangzhis)

Fk:loadTranslationTable{
  ["wk_heg__zhugezhan"] = "诸葛瞻",
  ["designer:wk_heg__zhugezhan"] = "教父&24&635",
  ["#wk_heg__zhugezhan"] = "困渊腾龙",

  ["wk_heg__zuilun"] = "罪论",
  [":wk_heg__zuilun"] = "锁定技，结束阶段，你执行并移除一项：1.横置；2.弃置手牌至一张；3.失去体力至1点；若均已执行过，则改为对一名其他角色造成1点伤害。",
  ["wk_heg__longfei"] = "龙飞",
  [":wk_heg__longfei"] = "主将技，阵法技，与你处于同一队列角色的准备阶段，你观看牌堆顶X张牌并将这些牌以任意顺序置于牌堆顶或牌堆底（X为与你处于同一队列角色数）。",
  ["wk_heg__kuangzhis"] = "匡志",
  [":wk_heg__kuangzhis"] = "副将技，此武将牌上单独的阴阳鱼个数-1；①与你势力相同的角色于其回合内首次造成伤害后，你可与其各摸一张牌；②当你进入濒死状态被救回后，你交换主副将，然后视为对一名与你势力不同且手牌数为其中最多的角色使用一张【决斗】。",

  ["wk_heg__zuilun-chain"] = "横置",
  ["wk_heg__zuilun-discard"] = "弃置手牌至一张",
  ["wk_heg__zuilun-losehp"] = "失去体力至1点",
  ["wk_heg__zuilun-choose"] = "罪论：你对一名其他角色造成1点伤害",

  ["#wk_heg__longfei_trigger"] = "龙飞",

  ["wk_heg__kuangzhis-drawcard"] = "匡志：你可与当前回合角色各摸一张牌",
  ["wk_heg__kuangzhis-choose"] = "匡志：选择一名手牌数全场最多且与你势力不同的角色，视为对其使用一张【决斗】",


  ["$wk_heg__zuilun1"] = "吾有三罪，未能除黄皓、制伯约、守国土。",
  ["$wk_heg__zuilun2"] = "唉，数罪当论，吾愧对先帝恩惠。",
  ["$wk_heg__longfei1"] = "",
  ["$wk_heg__longfei2"] = "",
  ["$wk_heg__kuangzhis1"] = "得父荫庇，平步青云。",
  ["$wk_heg__kuangzhis2"] = "吾自幼心怀父诫，方不愧父亲荫庇。",

  ["~wk_heg__zhugezhan"] = "临难而死义，无愧先父…",
}

local huaman = General(extension, "wk_heg__huaman", "shu", 4, 4, General.Female)
local xiangzhen = fk.CreateViewAsSkill{
  name = "wk_heg__xiangzhen",
  anim_type = "offensive",
  prompt = "#wk_heg__xiangzhen",
  frequency = Skill.Limited,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local card = Fk:cloneCard("savage_assault")
    card:addSubcards(Self:getCardIds(Player.Hand))
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and not player:isKongcheng()
  end,
  after_use = function (self, player, use)
    if player.hp > player:getHandcardNum() then
      player:drawCards(player.hp - player:getHandcardNum(), self.name)
    end
  end,
}

local mansi = fk.CreateTriggerSkill{
  name = "wk_heg__mansi",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.PreCardEffect, fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if event == fk.PreCardEffect then
      return player:hasSkill(self) and data.card.trueName == "savage_assault" and player.id == data.to
    else
      local events = player.room.logic:getActualDamageEvents(99, function(e)
        return e.data[1].card and e.data[1].card.trueName == "savage_assault"
      end, Player.HistoryTurn)
      return player:hasSkill(self) and #events > player.hp
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.PreCardEffect then
      return true
    else
      player:setSkillUseHistory(xiangzhen.name, 0, Player.HistoryGame)
    end
  end,
}

huaman:addSkill(mansi)
huaman:addSkill(xiangzhen)
Fk:loadTranslationTable{
  ["wk_heg__huaman"] = "花鬘",
  ["#wk_heg__huaman"] = "芳踪载馨",
  ["designer:wk_heg__huaman"] = "白兮",

  ["wk_heg__xiangzhen"] = "象阵",
  [":wk_heg__xiangzhen"] = "限定技，出牌阶段，你可将所有手牌当【南蛮入侵】使用，此牌结算后你将手牌摸至体力值。",
  ["wk_heg__mansi"] = "蛮嗣",
  [":wk_heg__mansi"] = "锁定技，【南蛮入侵】对你无效；每回合结束时，若本回合因【南蛮入侵】而受到伤害的角色数大于你的体力值，你复原此武将牌上所有技能。",

  ["#wk_heg__xiangzhen"] = "象阵：你可以将所有手牌当【南蛮入侵】使用，然后将手牌摸至体力上限",

  ["$wk_heg__xiangzhen1"] = "承父母庇护，得此福气。",
  ["$wk_heg__xiangzhen2"] = "多谢父母怜爱。",
  ["$wk_heg__mansi1"] = "南蛮女子，该当英勇善战！",
  ["$wk_heg__mansi2"] = "蛮族的力量，你可不要小瞧！",

  ["~wk_heg__huaman"] = "南蛮之地的花，还在开吗……",
}

local heqi = General(extension, "wk_heg__heqi", "wu", 4)

local yingzi = fk.CreateTriggerSkill{
  name = "wk_heg__heqi_yingzi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.DrawNCards},
  on_use = function(self, event, target, player, data)
    data.n = data.n + 1
  end,
}
local yingzi_maxcards = fk.CreateMaxCardsSkill{
  name = "#wk_heg__heqi_maxcards",
  fixed_func = function(self, player)
    if player:hasSkill(self) then
      return player.maxHp
    end
  end
}

local duanbing = fk.CreateTriggerSkill{
  name = "wk_heg__heqi_duanbing",
  anim_type = "offensive",
  events = {fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash" and
      table.find(player.room:getUseExtraTargets(data), function(id)
        return player:distanceTo(player.room:getPlayerById(id)) == 1
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getUseExtraTargets(data), function(id)
      return player:distanceTo(room:getPlayerById(id)) == 1
    end)
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#duanbing-choose", self.name, true)
    if #tos > 0 then
      self.cost_data = tos[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    table.insert(data.tos, {self.cost_data})
  end,
}

local qizhou = fk.CreateTriggerSkill{
  name = "wk_heg__qizhou",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Start
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local suits = {}
    for _, e in ipairs(player:getCardIds("e")) do
      table.insertIfNeed(suits, Fk:getCardById(e).suit)
    end
    if #suits > GetPolicyNum(player) then
      local num = #suits - GetPolicyNum(player)
      GetPolicy(room, player, num, self.name)
    else
      room:handleAddLoseSkills(player, 'wk_heg__heqi_yingzi|wk_heg__heqi_duanbing')
      room.logic:getCurrentEvent():findParent(GameEvent.Turn):addCleaner(function()
        room:handleAddLoseSkills(player, '-wk_heg__heqi_yingzi|-wk_heg__heqi_duanbing', nil, true, false)
      end)
    end
  end,
}

yingzi:addRelatedSkill(yingzi_maxcards)
heqi:addRelatedSkill(yingzi)
heqi:addRelatedSkill(duanbing)
heqi:addSkill(qizhou)
Fk:loadTranslationTable{
  ["wk_heg__heqi"] = "贺齐",
  ["#wk_heg__heqi"] = "",
    
  ["designer:wk_heg__heqi"] = "24",
  ["wk_heg__qizhou"] = "绮胄",
  [":wk_heg__qizhou"] = "准备阶段，若你的“战策”数小于你装备区内牌的花色数，你可将你的“战策”数调整至你装备区内牌的花色数，否则你获得“英姿”和“短兵”至本回合结束<br />"..
  "<font color = 'gray'>战策：部分角色可以获得“战策”，获得“战策”时，其随机从“战策”库中抽取等量的“战策”并视为拥有此“战策”对应的效果；拥有“战策”的角色可以在对应的时机发动“战策”上的效果，然后将此“战策”洗回“战策”堆。</font>",

  ["wk_heg__heqi_yingzi"] = "英姿",
  ["#wk_heg__heqi_maxcards"] = "英姿",
  ["wk_heg__heqi_duanbing"] = "短兵",
  [":wk_heg__heqi_yingzi"] = "锁定技，①摸牌阶段，你多摸一张牌；②你的手牌上限改为你的体力上限。",
  [":wk_heg__heqi_duanbing"] = "当你使用【杀】选择目标后，你可以令一名你距离为1的角色成为此牌的额外目标",

  ["$wk_heg__qizhou1"] = "",
  ["$wk_heg__qizhou2"] = "",
  
  ["~wk_heg__heqi"] = "",
}

local xuezong = General(extension, "wk_heg__xuezong", "wu", 3)
local dingjian = fk.CreateActiveSkill{
  name = "wk_heg__dingjian",
  anim_type = "offensive",
  can_use = function(self, player)
    return not player:isKongcheng()
  end,
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  card_num = 0,
  target_num = 0,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local get = room:getNCards(1)
    local card_get = Fk:getCardById(get[1])
    player:showCards(get)
    local old_mark = player:getMark("@wk_heg__dingjian-turn")
    if old_mark == 0 then old_mark = {} end
    local choices = {"wk_heg__dingjian_discard", "wk_heg__dingjian_forbidden"}
    if table.contains(old_mark, card_get:getSuitString(true)) or player:getMark("wk_heg__dingjian_forbidden_none-turn") > 0 then
      choices = {"wk_heg__dingjian_discard"}
    end
    local choice = room:askForChoice(player, choices, self.name)
    if choice == "wk_heg__dingjian_forbidden" then
      room:moveCards({
        ids = get,
        to = player.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        proposer = player.id
      })
      room:setPlayerMark(player, "wk_heg__dingjian_forbidden_none-turn", 1)
    else
      room:moveCards({
        ids = get,
        toArea = Card.DrawPile,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
      })
      local n = (player:getHandcardNum() + 1) // 2
      local cards = room:askForDiscard(player, n, n, false, self.name, false)
      local to_use = {}
      to_use = table.filter(cards, function (id)
        local card = Fk:getCardById(id)
        return room:getCardArea(id) == Card.DiscardPile and not player:prohibitUse(card) and card.suit == card_get.suit
      end)
      local use = U.askForUseRealCard(room, player, to_use, ".", self.name, "#wk_heg__dingjian-use", {expand_pile = to_use, extra_use = true}, true)
      if use then
        room:useCard(use)
      end
    end
  end,
}

local jiexun = fk.CreateTriggerSkill{
  name = "wk_heg__jiexun",
  events = {fk.TargetSpecifying},
  anim_type = "special",
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and H.compareKingdomWith(player, target) and data.firstTarget) then return false end
    if #AimGroup:getAllTargets(data.tos) == 1 and AimGroup:getAllTargets(data.tos)[1] == target.id  then
      return false
    end
    return true
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local card = target:drawCards(1, self.name)
    target:showCards(card)
    local targets = AimGroup:getAllTargets(data.tos)
    local tos = #targets == 1 and targets or room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__jiexun-choose-cancel:::" .. data.card:toLogString(), self.name, false)
    AimGroup:cancelTarget(data, tos[1])
    if Fk:getCardById(card[1]).suit == data.card.suit then
      -- local mark = U.getMark(target, "@wk_heg__jiexun-turn")
      local mark = target:getTableMark("@wk_heg__jiexun-turn")
      if table.insertIfNeed(mark, Fk:getCardById(card[1]):getSuitString(true)) then
        room:setPlayerMark(target, "@wk_heg__jiexun-turn", mark)
        -- mark = U.getMark(target, "_wk_heg__jiexun-turn")
        mark = target:getTableMark("_wk_heg__jiexun-turn")
        mark[Fk:getCardById(card[1]):getSuitString(true)] = player.id
        room:setPlayerMark(target, "_wk_heg__jiexun-turn", mark)
      end
    end
  end,
}

local jiexun_trigger = fk.CreateTriggerSkill{
  name = "#wk_heg__jiexun_trigger",
  events = {fk.AfterCardTargetDeclared},
  anim_type = "special",
  can_trigger = function (self, event, target, player, data)
    if target:getMark("@wk_heg__jiexun-turn") == 0 then return false end
    -- return U.getMark(target, "_wk_heg__jiexun-turn")[data.card:getSuitString(true)] == player.id
    return target:getTableMark("_wk_heg__jiexun-turn")[data.card:getSuitString(true)] == player.id and data.card.trueName ~= "threaten_emperor"
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = room:getUseExtraTargets(data)
    local to = room:askForChoosePlayers(target, targets, 1, 1, "#wk_heg__jiexun-choose-add:::" .. data.card:toLogString(), self.name, true)
    if #to > 0 then TargetGroup:pushTargets(data.tos, to[1]) end
    -- local mark = U.getMark(target, "@wk_heg__jiexun-turn")
    local mark = target:getTableMark("@wk_heg__jiexun-turn")
    table.removeOne(mark, data.card:getSuitString(true))
    if #mark == 0 then mark = 0 end
    room:setPlayerMark(target, "@wk_heg__jiexun-turn", mark)
    -- mark = U.getMark(target, "_wk_heg__jiexun-turn")
    mark = target:getTableMark("_wk_heg__jiexun-turn")
    mark[data.card:getSuitString(true)] = nil
    room:setPlayerMark(target, "_wk_heg__jiexun-turn", mark)
  end,
}

-- dingjian:addRelatedSkill(dingjian_prohibit)
xuezong:addSkill(dingjian)

jiexun:addRelatedSkill(jiexun_trigger)
xuezong:addSkill(jiexun)
Fk:loadTranslationTable{
  ["wk_heg__xuezong"] = "薛综",
  ["designer:wk_heg__xuezong"] = "教父",
  ["#wk_heg__xuezong"] = "彬彬之玉",

  ["wk_heg__dingjian"] = "定谏",
  [":wk_heg__dingjian"] = "出牌阶段，你可展示牌堆顶一张牌并选择一项：1.弃置半数手牌（向上取整），然后使用其中一张与展示牌花色相同的牌；2.获得此牌，然后你本回合不能选择此项。",
  ["wk_heg__jiexun"] = "诫训",
  [":wk_heg__jiexun"] = "与你势力相同角色使用牌指定其以外的角色为目标时，你可令其摸一张牌并展示之并取消此牌一个目标，若两牌花色相同，其本回合下次使用此花色的牌选择目标后，其可以额外指定一个目标。",

  ["#wk_heg__dingjian-use"] = "定谏：你可以使用其中一张牌",
  ["#wk_heg__jiexun-choose-add"] = "诫训：你可以为 %arg 额外指定一个合法目标",
  ["#wk_heg__jiexun-choose-cancel"] = "诫训：请为 %arg 取消一个目标",
  ["@wk_heg__jiexun-turn"] = "诫训",
  ["@wk_heg__dingjian-turn"] = "定谏",
  ["#wk_heg__jiexun_trigger"] = "诫训",
  ["dingjian"] = "定谏",

  ["wk_heg__dingjian_discard"] = "弃牌，使用其中一张",
  ["wk_heg__dingjian_forbidden"] = "获得牌，不能再选择此项",

  ["$wk_heg__dingjian1"] = "礼尚往来，乃君子风范。",
  ["$wk_heg__dingjian2"] = "以子之矛，攻子之盾。",
  ["$wk_heg__jiexun1"] = "帝王应以社稷为重，以大观为主。",
  ["$wk_heg__jiexun2"] = "吾冒昧进谏，只求陛下思虑。",
  ["~wk_heg__xuezong"] = "尔等竟做如此有辱斯文之事。",
}

local sunliang = General(extension, "wk_heg__sunliang", "wu", 3, 3, General.Male)
local chitao = fk.CreateTriggerSkill{
  name = "wk_heg__chitao",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and player ~= target and target.phase == Player.Finish) then return false end
    local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function(e)
      local use = e.data[1]
      return table.contains(TargetGroup:getRealTargets(use.tos), player.id) and use.from == target.id
    end, Player.HistoryTurn)
    return #events > 0
  end,
  on_cost = function (self, event, target, player, data)
    local targets = table.map(table.filter(player.room.alive_players, function (p)
      return p ~= player and p ~= target end), Util.IdMapper)
    local id, card = player.room:askForChooseCardAndPlayers(player, targets, 1, 1, ".", "#wk_heg__chitao-choose", self.name, true)
    if #id > 0 then
      self.cost_data = {card, id[1]}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:moveCards({
      ids = table.reverse({self.cost_data[1]}),
      from = player.id,
      toArea = Card.DrawPile,
      moveReason = fk.ReasonPut,
      skillName = self.name,
      proposer = player.id,
    })
    local to = room:getPlayerById(self.cost_data[2])
    room:useVirtualCard("slash", nil, to, target, self.name)
  end,
}

local chezheng = fk.CreateTriggerSkill{
  name = "wk_heg__chezheng",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetConfirming, fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if event == fk.TargetConfirming then
      return player:hasSkill(self) and player ~= target and not player:inMyAttackRange(target) and data.from == player.id
    else
      return player:hasSkill(self) and data.tos and data.card.trueName == "slash" and 
        table.find(TargetGroup:getRealTargets(data.tos), function(id)
         local p = player.room:getPlayerById(id)
        return id ~= player.id and not p.dead and not player:inMyAttackRange(p) end)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TargetConfirming then
      AimGroup:cancelTarget(data, target.id)
      return true
    else
      local targets = TargetGroup:getRealTargets(data.tos)
      for _, pid in ipairs(targets) do
        local p = room:getPlayerById(pid)
        if not p.dead and not player.dead and not player:inMyAttackRange(p) then
          local choices = {"wk_heg__chezheng_damage::"..p.id, "Cancel"}
          local choice = room:askForChoice(player, choices, self.name)
          if choice ~= "Cancel" then
            room:damage{
              from = player,
              to = p,
              damage = 1,
              skillName = self.name
            }
            if not p.dead then
              local choices2 = {"wk_heg__chezheng_remove", "wk_heg__chezheng_loseHp"}
              local choice2 = room:askForChoice(player, choices2, self.name)
              if choice2 == "wk_heg__chezheng_remove" then
                local isDeputy = H.inGeneralSkills(player, self.name) 
                if isDeputy then
                  H.removeGeneral(player.room, player, isDeputy == "d") 
                end
              else
                room:loseHp(player, 1, self.name)
              end
            end
          end
        end
      end
    end
  end,
}

sunliang:addSkill(chitao)
sunliang:addSkill(chezheng)
Fk:loadTranslationTable{
  ["wk_heg__sunliang"] = "孙亮",
  ["#wk_heg__sunliang"] = "盘龙陷沼",
  ["designer:wk_heg__sunliang"] = "小曹神",

  ["wk_heg__chitao"] = "敕讨",
  [":wk_heg__chitao"] = "其他角色的结束阶段，若你本回合成为过其使用牌的目标，你可将一张牌置于牌堆顶，令一名除其外的其他角色视为对其使用一张【杀】。",
  ["wk_heg__chezheng"] = "掣政",
  [":wk_heg__chezheng"] = "锁定技，你攻击范围外的其他角色：1.成为你使用牌的目标时，取消之；2.成为【杀】的目标结算后，你可以对其造成1点伤害，然后若其未死亡，你失去1点体力或移除此武将牌。",

  ["#wk_heg__chitao-choose"] = "敕讨：你可以将一张牌置于牌堆顶并选择一名除你与当前回合外的角色，其对当前回合角色视为使用一张【杀】",
  ["wk_heg__chezheng_damage"] = "对 %dest 造成伤害",
  ["wk_heg__chezheng_remove"] = "移除武将",
  ["wk_heg__chezheng_loseHp"] = "失去体力",

  ["$wk_heg__chitao1"] = "子通专恣，必谋而诛之！",
  ["$wk_heg__chitao2"] = "孙綝久专，不可久忍，必溃诛！",
  ["$wk_heg__chezheng1"] = "风驰电掣，政权不怠！",
  ["$wk_heg__chezheng2"] = "连屏掣政，实为艰事。",

  ["~wk_heg__sunliang"] = "今日欲诛逆臣而不得，方知机事不密则害成…",
}

local mengyou = General(extension, "wk_heg__mengyou", "qun", 4)
local mingjiao = fk.CreateTriggerSkill{
  name = "wk_heg__mingjiao",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.GeneralRevealed, "fk.HegLosePolicy", fk.PreCardEffect},
  can_trigger = function (self, event, target, player, data)
    if event == fk.PreCardEffect then
      return player:hasSkill(self) and data.card.trueName == "savage_assault" and player.id == data.to
    elseif event == fk.GeneralRevealed then
      if player:getMark("wk_heg__mingjiao_show") == 0 and player:hasSkill(self) then
        for _, v in pairs(data) do
          if table.contains(Fk.generals[v]:getSkillNameList(), self.name) then return true end
        end
      end
    else
      return player:hasSkill(self) and data[1] == player
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.GeneralRevealed then
      room:setPlayerMark(player, "wk_heg__mingjiao_show", 1)
      GetPolicy(room, player, 2, self.name)
    elseif event == "fk.HegLosePolicy" then
      GetPolicy(room, player, 1, self.name)
    else
      return true
    end
  end
}

mengyou:addSkill(mingjiao)
Fk:loadTranslationTable{
  ["wk_heg__mengyou"] = "孟优",
  ["#wk_heg__mengyou"] = "",
    
  ["designer:wk_heg__mengyou"] = "猪&静谦",
  ["wk_heg__mingjiao"] = "鸣角",
  [":wk_heg__mingjiao"] = "锁定技，①【南蛮入侵】对你无效；②当你首次明置此武将牌后，你获得两张“战策”；③当你失去一张“战策”后，你获得一张“战策”<br />"..
  "<font color = 'gray'>战策：部分角色可以获得“战策”，获得“战策”时，其随机从“战策”库中抽取等量的“战策”并视为拥有此“战策”对应的效果；拥有“战策”的角色可以在对应的时机发动“战策”上的效果，然后将此“战策”洗回“战策”堆。</font>",

  ["$wk_heg__mingjiao1"] = "",
  ["$wk_heg__mingjiao2"] = "",
  
  ["~wk_heg__mengyou"] = "",
}


local wangyun = General(extension, "wk_heg__wangyun", "qun", 4)
wangyun.mainMaxHpAdjustedValue = -1
local jingong = fk.CreateTriggerSkill{
  name = "wk_heg__jingong",
  anim_type = "drawcard",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and player.phase == Player.Finish) then return false end
    self.cost_data = {}
    return #player.room.logic:getActualDamageEvents(2, function(e)
      if e.data[1].from == player then
        return table.insertIfNeed(self.cost_data, e.data[1].to)
      end
      return false
    end, Player.HistoryTurn) > 0
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if #self.cost_data == 1 then
      room:notifySkillInvoked(player, self.name, "drawcard")
      player:drawCards(2, self.name)
    else
      room:notifySkillInvoked(player, self.name, "negative")
      room:loseHp(player, 1, self.name)
    end
  end,
}

local mingjie = fk.CreateTriggerSkill{
  name = "wk_heg__mingjie",
  relate_to_place = 'm',
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and player.phase == Player.Start
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(room:getOtherPlayers(player), Util.IdMapper)
    local to = player.room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__mingjie-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local mark = U.getMark(to, "@@wk_heg__mingjie-turn")
    table.insert(mark, player.id)
    room:setPlayerMark(to, "@@wk_heg__mingjie-turn", mark)
  end,
}

local lianji = fk.CreateTriggerSkill{
  name = "wk_heg__lianji",
  anim_type = "special",
  events = {fk.TargetSpecifying},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target == player and data.card:isCommonTrick()
      and data.tos and #AimGroup:getAllTargets(data.tos) == 1 and (not data.card:isVirtual() or #data.card.subcards == 0)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = AimGroup:getAllTargets(data.tos)
    local tos = #targets == 1 and targets or room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__lianji-choose:::" .. data.card:toLogString(), self.name, false)
    AimGroup:cancelTarget(data, tos[1])
    local to = room:getPlayerById(tos[1])
    if to:getMark("@@wk_heg__lianji_must-turn") ~= 0 then
      H.askCommandTo(player, to, self.name, true)
    else
      if not H.askCommandTo(player, to, self.name) then
        room:setPlayerMark(to, "@@wk_heg__lianji_must-turn", 1)
      end
    end
  end,
}

local mingjie_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__mingjie_delay",
  mute = true,
  events = {fk.AfterCardTargetDeclared, fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardTargetDeclared then
      if target == player and (data.card.type == Card.TypeBasic or data.card:isCommonTrick()) and data.card.trueName ~= "threaten_emperor" then
        local mark
        local targets = table.filter(room:getUseExtraTargets(data), function (id)
          mark = room:getPlayerById(id):getMark("@@wk_heg__mingjie-turn")
          return type(mark) == "table" and table.contains(mark, player.id)
        end)
        if #targets > 0 then
          self.cost_data = targets
          return true
        end
      end
    elseif event == fk.DamageCaused then
      local mark = data.to:getMark("@@wk_heg__mingjie-turn")
      return player == target and type(mark) == "table" and table.contains(mark, player.id)
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardTargetDeclared then
      local tos = room:askForChoosePlayers(player, self.cost_data, 1, #self.cost_data,
        "#mingjiew-choose:::"..data.card:toLogString(), "mingjiew", true)
      if #tos > 0 then
        table.forEach(tos, function (id)
          table.insert(data.tos, {id})
        end)
      end
    else
      return true
    end
  end,
}

wangyun:addSkill(jingong)
wangyun:addSkill(lianji)
wangyun:addSkill(mingjie)
mingjie:addRelatedSkill(mingjie_delay)
Fk:loadTranslationTable{
  ["wk_heg__wangyun"] = "王允",
  ["designer:wk_heg__wangyun"] = "教父&静谦&猪",
  ["#wk_heg__wangyun"] = "矜贤之国纪",

  ["wk_heg__jingong"] = "矜功",
  [":wk_heg__jingong"] = "锁定技，结束阶段，若本回合受到你造成伤害的角色数：为1，你摸两张牌；大于1，你失去1点体力。",
  ["wk_heg__lianji"] = "连计",
  [":wk_heg__lianji"] = "当你使用非转化的普通锦囊牌指定唯一目标时，你可取消之，对其发起“军令”，若其不执行，直至本回合结束，你以此法对其发起的“军令”改为强制执行。",
  ["wk_heg__mingjie"] = "铭戒",
  [":wk_heg__mingjie"] = "主将技，此武将牌上单独的阴阳鱼个数-1；准备阶段，你可选择一名其他角色，你于本回合内使用牌可额外指定其为目标且防止对其造成的伤害。",

  ["#wk_heg__lianji-choose"] = "连计：你可以取消 %arg 的唯一目标且对其发起“军令”",
  ["@@wk_heg__mingjie-turn"] = "铭戒",
  ["@@wk_heg__lianji_must-turn"] = "连计 强制军令",

  ["#wk_heg__mingjie-choose"] = "铭戒：你可以选择一名其他角色，防止本回合对其造成的伤害且本回合使用牌可以额外指定其为目标",

  ["$wk_heg__jingong1"] = "董贼旧部，可尽诛之！",
  ["$wk_heg__jingong2"] = "若无老夫之谋，尔等皆化为腐土也。",
  ["$wk_heg__lianji1"] = "两计扣用，以催强势。",
  ["$wk_heg__lianji2"] = "容老夫细细思量。",
  ["$wk_heg__mingjie1"] = "大公至正，恪忠义于国。",
  ["$wk_heg__mingjie2"] = "此生柱国之志，铭恪于胸。",
  ["~wk_heg__wangyun"] = "获罪于君，当伏大辟以谢天下…",
}

local liru = General(extension, "wk_heg__liru", "qun", 3)
local fencheng = fk.CreateActiveSkill{
  name = "wk_heg__fencheng",
}
local mieji = fk.CreateTriggerSkill{
  name = "wk_heg__mieji",
}
liru.hidden = true
liru:addSkill(fencheng)
liru:addSkill(mieji)
Fk:loadTranslationTable{
  ["wk_heg__liru"] = "李儒",
  ["designer:wk_heg__wangyun"] = "猪",
  ["wk_heg__fencheng"] = "焚城",
  [":wk_heg__fencheng"] = "你可将一张黑色手牌当【火攻】使用，此牌结算后所有受到此牌伤害的目标角色视为使用一张【火烧联营】，若此牌未造成伤害，此技能失效至本回合结束。",
  ["wk_heg__mieji"] = "灭计",
  [":wk_heg__mieji"] = "限定技，回合结束时，你可以令所有角色依次选择两项：1.叠置；2.摸两张牌；3.获得【鸩饮】至你的回合开始前。",

  ["~wk_heg__liru"] = "",
}
--[[
local liru = General(extension, "wk_heg__liru", "qun", 3)
local fencheng = fk.CreateActiveSkill{
  name = "wk_heg__fencheng",
  anim_type = "offensive",
  card_num = 0,
  target_num = 0,
  frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local targets = room:getOtherPlayers(player)
    local n = 0
    for _, target in ipairs(targets) do
      local total = #target:getCardIds{Player.Hand, Player.Equip}
      if total < n + 1 then
        room:damage{
          from = player,
          to = target,
          damage = 1,
          damageType = fk.FireDamage,
          skillName = self.name,
        }
        n = 0
      else
        local cards = room:askForDiscard(target, n + 1, 999, true, self.name, true, ".", "#wk_heg__fencheng-discard:::"..tostring(n + 1))
        if #cards == 0 then
          room:damage{
            from = player,
            to = target,
            damage = 1,
            damageType = fk.FireDamage,
            skillName = self.name,
          }
          n = 0
        else
          n = #cards
        end
      end
    end
  end
}

liru:addSkill("juece")
liru:addSkill("mieji")
liru:addSkill(fencheng)
liru:addCompanions("ld__dongzhuo")
Fk:loadTranslationTable{
  ["wk_heg__liru"] = "李儒",
  ["designer:wk_heg__liru"] = "新月",
  ["#wk_heg__liru"] = "暴主狐婿",

  ["wk_heg__juece"] = "绝策",
  [":wk_heg__juece"] = "结束阶段，你可以对一名没有手牌的其他角色造成1点伤害。",
  ["wk_heg__mieji"] = "灭计",
  [":wk_heg__mieji"] = "出牌阶段限一次，你可以将一张黑色锦囊牌置于牌堆顶并选择一名其他角色，然后令该角色选择一项：1.弃置一张锦囊牌；2.依次弃置两张非锦囊牌。",
  ["wk_heg__fencheng"] = "焚城",
  [":wk_heg__fencheng"] = "限定技，出牌阶段，你可以令所有其他角色依次选择一项：1.弃置至少X+1张牌（X为该角色的上家以此法弃置牌的数量）；"..
  "2.受到你造成的1点火焰伤害。",
  ["#wk_heg__fencheng-discard"] = "焚城：弃置至少%arg张牌，否则受到1点火焰伤害",

  ["$wk_heg__juece1"] = "哼！你走投无路了。",
  ["$wk_heg__juece2"] = "无用之人，死！",
  ["$wk_heg__mieji1"] = "宁错杀，无放过！",
  ["$wk_heg__mieji2"] = "你能逃得出我的手掌心吗？",
  ["$wk_heg__fencheng1"] = "我得不到的，你们也别想得到！",
  ["$wk_heg__fencheng2"] = "让这一切都灰飞烟灭吧！哼哼哼哼……",
  ["~wk_heg__liru"] = "如遇明主，大业必成……",
}
--]]--
return extension
